package com.zhkj.lib.http

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object HttpServiceFactory {

    private val mHttpClientBuilder: OkHttpClient.Builder = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS) //连接超时时间
        .readTimeout(10, TimeUnit.SECONDS) //读取超时时间设置
        .writeTimeout(10, TimeUnit.SECONDS) //写入超时时间设置
        .retryOnConnectionFailure(true)//错误重连

    init {
//        if (BuildConfig.DEBUG) {
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        mHttpClientBuilder.addInterceptor(loggingInterceptor)
        mHttpClientBuilder.addInterceptor(HeadersInterceptor())
//        }
    }

    fun <ApiService> createService(clazz: Class<ApiService>, baseUrl: String): ApiService {
        val retrofit = Retrofit.Builder().client(mHttpClientBuilder.build())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl(baseUrl)
            .build()
        return retrofit.create(clazz)
    }
}